package com.jse.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.nutz.log.Log;
import org.nutz.log.Logs;

public class MysqlBak {
	private static Process p;
	private static Log log=Logs.get();
	
	public static void main(String[] args) {
		exec("ty", "d:/");
	}

	public static void exec(String databases,String path) {
		exec(databases,"root","chaojimima=123$",path);
	}
	/**
	 * 数据库备份任务
	 * 
	 * @param databases
	 *            数据库名称
	 * @param path
	 *            路径例子 c:/xxx/
	 * @throws FileNotFoundException
	 */
	public static void exec(String databases,String username,String pwd,String path) {
		Runtime runtime = Runtime.getRuntime();
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
		String currentTime = dateFormat.format(calendar.getTime());
		PrintStream print = null;
		try {
			p = runtime.exec("cmd /c mysqldump -u"+username+" -p"+pwd+" -B " + databases + " >" + path + currentTime
					+ ".sql.bak");
		} catch (IOException e) {
			log.error(e);
			p.destroy();
			try {
				print = new PrintStream(currentTime + "_backup_err.log");
				dateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
				currentTime = dateFormat.format(calendar.getTime());
				print.println(currentTime + "  backup failed.");
				e.printStackTrace(print);
				print.flush();
			} catch (FileNotFoundException e1) {
				log.error(e1);
			}

		} finally {
			if (print != null) {
				print.close();
			}
		}
	}
}